import * as api from '@/services/admin';
import { CloseCircleOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { FooterToolbar } from '@ant-design/pro-layout';
import { Card, message, Popover, Space, Tree } from 'antd';
import md5 from 'blueimp-md5';
import React, { useRef, useState } from 'react';
import { history, useRequest } from 'umi';

import { PageContainer } from '@ant-design/pro-components';
import { useMatch } from '@umijs/max';
import styles from '../Form.less';

const fieldLabels = {
  username: '用户名',
  password: '密码',
  name: '姓名',
  status: '状态',
  funcRightIds: '功能权限',
  remark: '备注',
};

const Form: React.FC = (props: any) => {
  // const { match } = props;
  // let userId = match.params.id ? parseInt(match.params.id, 10) : undefined;
  // if (!userId || userId < 1) {
  //   userId = undefined;
  // }
  const match = useMatch({ path: '/system/admin/update/:id' });
  //console.log('props: ', props, ' location:', location, ' match: ', match);

  let userId = match?.params?.id ? parseInt(match.params.id, 10) : undefined;
  if (!userId || userId < 1) {
    userId = undefined;
  }

  const [funcRightTree, setFuncRightTree] = useState<API.TreeItem[]>([]);
  const [current, setCurrent] = useState<API.AdminModel | undefined>(undefined);
  const [checkedFuncRightIds, setCheckedFuncRightIds] = useState<string[]>([]);

  const formRef = useRef<ProFormInstance>();

  const [error, setError] = useState<API.ErrorField[]>([]);
  const getErrorInfo = (errors: API.ErrorField[]) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as string;
      return (
        <li
          key={key}
          className={styles.errorListItem}
          onClick={() => scrollToField(key)}
        >
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const { loading } = useRequest(async () => {
    return loadData();
  });

  const loadData = async () => {
    if (userId && userId > 0) {
      const result = await api.get(userId);
      if (result.success === true && result.data) {
        setCurrent(result.data);
        setFuncRightTree(result.funcRightTree);
        setCheckedFuncRightIds(result.data.funcRightIds);
      }
    } else {
      const result = await api.funRightTree();
      if (result.success === true && result.data) {
        setFuncRightTree(result.data);
      }
    }

    return Promise.resolve({
      loading: false,
    });
  };

  const onFinish = async (record: API.AdminModel) => {
    setError([]);

    let result: API.Result;
    if (record.password && record.password !== '') {
      record.password = md5(record.password);
    }
    record.funcRightIds = checkedFuncRightIds || [];

    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      message.success('提交成功');

      history.back();
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  const onReset = () => {
    setError([]);
  };

  const onFuncRightCheck = (checkedKeys: any, info: any) => {
    console.log('onCheck', checkedKeys, info);

    setCheckedFuncRightIds(checkedKeys || []);
  };

  return (
    <PageContainer>
      {loading && <Card style={{ minHeight: 640 }} loading={loading} />}
      {!loading && (
        <Card>
          <ProForm<API.AdminModel>
            formRef={formRef}
            layout="vertical"
            style={{ margin: 'auto', marginTop: 8, maxWidth: 600 }}
            hideRequiredMark
            initialValues={current ? current : { status: true }}
            submitter={{
              render: (props, doms) => {
                return (
                  <FooterToolbar>
                    <Space>
                      {getErrorInfo(error)}
                      {doms[0]}
                      {doms[1]}
                    </Space>
                  </FooterToolbar>
                );
              },
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            onReset={onReset}
          >
            <ProFormText
              label={fieldLabels.username}
              name="username"
              rules={[{ required: true }]}
              placeholder="请输入用户名"
            />
            <ProFormText
              label={fieldLabels.password}
              name="password"
              rules={[{ required: !current }]}
              placeholder="请输入密码"
            />
            <ProFormText
              label={fieldLabels.name}
              name="name"
              rules={[{ required: true }]}
              placeholder="请输入姓名"
            />
            <ProFormSwitch label={fieldLabels.status} name="status" />
            {!current?.super && funcRightTree.length > 0 && (
              <ProForm.Item
                label={fieldLabels.funcRightIds}
                name="funcRightIds"
              >
                <Tree
                  className={styles.funcRightTree}
                  height={542}
                  checkable
                  // checkStrictly={true}
                  selectable={false}
                  defaultExpandAll
                  defaultCheckedKeys={checkedFuncRightIds}
                  treeData={funcRightTree}
                  onCheck={onFuncRightCheck}
                />
              </ProForm.Item>
            )}
            <ProFormTextArea name="remark" label="备注" />
          </ProForm>
        </Card>
      )}
    </PageContainer>
  );
};

export default Form;
